package com.shoute.ai.config;


import org.springframework.ai.embedding.TokenCountBatchingStrategy;
import org.springframework.ai.openai.OpenAiEmbeddingModel;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.vectorstore.redis.RedisVectorStore;
import org.springframework.boot.autoconfigure.data.redis.RedisConnectionDetails;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPooled;

import java.util.Arrays;

@Configuration
public class RedisConfiguration {


    /**
     * 创建并配置JedisPooled实例
     * 该方法通过Spring的@Bean注解定义了一个Bean，使得Spring IoC容器可以管理该Bean的生命周期和依赖
     * JedisPooled是一个封装了Jedis连接池的类，用于高效地管理Redis连接
     *
     * @param redisConnectionDetails Redis连接详情，包含了连接Redis所需的信息，如主机、端口、用户名和密码
     * @return 返回一个配置好的JedisPooled实例，用于与Redis进行交互
     */
    @Bean
    public JedisPooled jedisPooled(RedisConnectionDetails redisConnectionDetails) {
        // 使用从redisConnectionDetails中提取的连接信息初始化JedisPooled实例
        // 包括主机、端口、用户名和密码，这些信息是连接Redis服务器所必需的
        return new JedisPooled(redisConnectionDetails.getStandalone().getHost(),
                redisConnectionDetails.getStandalone().getPort());
    }


    /**
     * 创建RedisStack向量数据库
     * @param embeddingModel 嵌入模型
     */

    @Bean
    public VectorStore redisVectorStore(JedisPooled jedisPooled, OpenAiEmbeddingModel embeddingModel) {

        return RedisVectorStore.builder(jedisPooled, embeddingModel)
                .indexName("docs_index")
                .prefix("doc:")
                .contentFieldName("content")
                .initializeSchema(true)
                .batchingStrategy(new TokenCountBatchingStrategy())
                .metadataFields(Arrays.asList(RedisVectorStore.MetadataField.text("file_fingerprint"),RedisVectorStore.MetadataField.text("source")))
                .build();
    }
}
